#!/usr/bin/python
import os
import sys
from subprocess import Popen, PIPE, call

call(["sed","-i","s/.*nightly/#&/","/etc/apt/sources.list"])
call(["sed","-i","s/.*custom/#&/","/etc/apt/sources.list"])

aptitude_installed = False;

dpkg_selections_output = Popen(["dpkg", "--get-selections"],stdout=PIPE).communicate()[0].splitlines()
held_packages = []
for line in dpkg_selections_output:
	if "hold" in line:
		word = line.split()
		held_packages.append(word[0])
	if "aptitude" in line:
		word = line.split()
		if word[1] == "install" and word[0] == "aptitude":
			aptitude_installed = True;


if aptitude_installed == True:
	aptitude_search_output = Popen(["aptitude","search","~ahold"],stdout=PIPE).communicate()[0].splitlines()
	for line in aptitude_search_output:
		word = line.split()
		held_packages.append(word[1])


installed_packages_output = Popen(["dpkg","-l","szarp-*"],stdout=PIPE).communicate()[0].splitlines()
installed = []
for line in installed_packages_output:
	if "szarp" in line:
		word = line.split()
		if word[0] == "ii" and "szarp" in word[1]:
			if not "custom" in word[2]:
				installed.append(word[1])
		elif word[0] == "hi" and "szarp" in word[1]:
			exit("jeden z pakietow szarpa jest holdowany")

dependencies = []
for szarp in installed:
	dependencies_output = Popen(["apt-cache", "show", szarp],stdout=PIPE).communicate()[0].splitlines()
	for line in dependencies_output:
		if "Depends:" in line:
			line = line.split()
			for word in line:
				if not word == "Depends:" and not word == "|":
					if word != "(>=" and not ")" in word:
						word = word.replace(",","")
						dependencies.append(word)

pkg_hold_and_dependent = set(dependencies) & set(held_packages)
if len(pkg_hold_and_dependent) != 0:
	print "Z powodu zachowanych paczek nie update'ujemy:"
	for pkg in pkg_hold_and_dependent:
		print pkg
	exit()
call(["apt-get","update"])
call(["apt-get","install","--only-upgrade","-y"]+ installed )
